package com.gxa.p2p.service.impl;

import com.gxa.p2p.common.enum1.ExceptionCode;
import com.gxa.p2p.common.exception.MyException;
import com.gxa.p2p.mapper.BorrowuserMapper;
import com.gxa.p2p.mapper.MarkImgsMapper;
import com.gxa.p2p.mapper.MarkMapper;
import com.gxa.p2p.mapper.RepaymentMapper;
import com.gxa.p2p.pojo.*;
import com.gxa.p2p.service.MarkService;
import com.gxa.p2p.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.*;

/**
 * @author Bei
 * @date 2021/10/26 16:27
 */
@Service
@Transactional(rollbackFor = Throwable.class)
public class MarkServiceImpl implements MarkService {

    @Autowired
    MarkImgsMapper markImgsMapper;

    @Autowired
    MarkMapper markMapper = null;

    @Autowired
    BorrowuserMapper borrowuserMapper;

    @Autowired
    RepaymentMapper repaymentMapper;



    /**
     *廖泓宇
     * 接口13 中标管理的包含模糊的全查询接口（返回字段不同）
     */




    @Override
    public List<Map> findAllLikeByPageZB(String legalName, String phone, Integer page, Integer size) {
        markMapper.updateShelfTime();

        List<Map> allLikeByPageZB = markMapper.findAllLikeByPageZB(legalName, phone, (page - 1) * size, size);
        return allLikeByPageZB;
    }

    @Override
    public Integer findAllLikeByPageZBCount(String legalName, String phone) {
        Integer allLikeByPageZBCount = markMapper.findAllLikeByPageZBCount(legalName, phone);
        return allLikeByPageZBCount;
    }


    @Override
    public List<Map> findAllLikeByPageFS(String legalName, String phone, Boolean progress, Integer page, Integer size) {
            List<Map> allLikeByPageFS = markMapper.findAllLikeByPageFS(legalName, phone, progress,(page - 1) * size, size);
            return allLikeByPageFS;
    }

    @Override
    public Integer findAllLikeByPageFSCount(String legalName, String phone, Boolean progress) {
        Integer allLikeByPageFS = markMapper.findAllLikeByPageFSCount(legalName, phone, progress);
        return allLikeByPageFS;

    }

    @Override
    public List<Map> findAllLikeByPageAJ(String legalName, String phone,Integer page, Integer size,String state1,String state2,String state3,String state4,String state5,String state6,String state7,String state8,String state9,String state10) {
        List<Map> allLikeByPageAJ = markMapper.findAllLikeByPageAJ(legalName, phone, (page - 1) * size, size,state1,state2,state3,state4,state5,state6,state7,state8,state9,state10);
        return allLikeByPageAJ;
    }

    @Override
    public List<MarkBrrowUserVo> findAllLikeByPageAJVO(String legalName, String phone, String state1, String state2, String state3, String state4, String state5, String state6, String state7, String state8, String state9, String state10) {
        List<MarkBrrowUserVo> allLikeByPageAJ = markMapper.findAllLikeByPageAJVo(legalName, phone,state1,state2,state3,state4,state5,state6,state7,state8,state9,state10);
        return allLikeByPageAJ;
    }

    @Override
    public Integer findAllLikeByPageAJCount(String legalName, String phone, String state1, String state2, String state3, String state4, String state5, String state6, String state7, String state8, String state9, String state10) {
        Integer allLikeByPageAJCount = markMapper.findAllLikeByPageAJCount(legalName, phone, state1, state2, state3, state4, state5, state6, state7, state8, state9, state10);
        return allLikeByPageAJCount;
    }

    @Override
    public void ceMark(Long id, String remarks3) {
        markMapper.ceMark(id, remarks3);
    }

    @Override
    public void DoubleExamMark(Long id, Boolean state, String remarks2) {
        String state1 = "流标";
        if (state){
            state1 = "还款中";
        }
        markMapper.DoubleExamMark(id, state1, remarks2,new Timestamp(System.currentTimeMillis()));

    }

    @Override
    public void updateZB(Mark mark) {
        markMapper.updateZB(mark);
    }

    @Override
    public void updateMarkClass(Markclass markclass) {
        markMapper.updateMarkClass(markclass);
    }

    @Override
    public void subMard(Mark mark) throws MyException {

        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        Long did = mark.getDid();
        Borrowuser borrowuser = borrowuserMapper.selectById(did);
        if (borrowuser!=null) {
            if (!StringUtil.isEmpty(borrowuser.getPhone())) {
                mark.setPhone(borrowuser.getPhone());
            }
            //设置利息管理月率
            Param param = markMapper.findParamByName("利息管理月率");
            if(param!=null){
                double v = param.getValues() / (100*1.0d);
                mark.setManageProRate(v);
            }else {
                mark.setManageProRate(0.01d);
            }
            //取出图片
            List<String> img = mark.getImg();
            List<String> materialImg = mark.getMaterialImg();
            //进入这个接口就是新标待审
            mark.setState("新标待审核");
            //如果是对暂存的标的修改提交，对原来的标再修改
            if(mark.getId()!=null){
                Mark byId = markMapper.findById(mark.getId());
                if (byId!=null) {
                    //存图
                    if (img!=null && img.size()!=0) {
                        for (String name : img) {
                            MarkImgs markImgs = new MarkImgs();
                            markImgs.setMid(byId.getId());
                            markImgs.setImgName(name);
                            markImgs.setState(2);
                            markImgsMapper.add(markImgs);
                        }
                    }
                    if (materialImg!=null && materialImg.size()!=0) {
                        for (String name : materialImg) {
                            MarkImgs markImgs = new MarkImgs();
                            markImgs.setMid(byId.getId());
                            markImgs.setImgName(name);
                            markImgs.setState(1);
                            markImgsMapper.add(markImgs);
                        }
                    }
                    //修改标
                    mark.setSubmitTime(timestamp);
                    markMapper.update(mark);
                    return;
                }
            }
            //新增标
            mark.setInsertTime(timestamp);
            mark.setSubmitTime(timestamp);
            //新增标返回id
            markMapper.addMark(mark);
            if (img!=null && img.size()!=0) {
                for (String name : img) {
                    MarkImgs markImgs = new MarkImgs();
                    markImgs.setMid(mark.getId());
                    markImgs.setImgName(name);
                    markImgs.setState(2);
                    markImgsMapper.add(markImgs);
                }
            }
            if (materialImg!=null && materialImg.size()!=0) {
                for (String name : materialImg) {
                    MarkImgs markImgs = new MarkImgs();
                    markImgs.setMid(mark.getId());
                    markImgs.setImgName(name);
                    markImgs.setState(1);
                    markImgsMapper.add(markImgs);
                }
            }
            return;
        }
        throw new MyException(ExceptionCode.NO_ID);

    }

    @Override
    public void tempMard(Mark mark) throws MyException {
        Long did = mark.getDid();
        Borrowuser borrowuser = borrowuserMapper.selectById(did);
        System.out.println(borrowuser);
        if (borrowuser!=null) {
            if (!StringUtil.isEmpty(borrowuser.getPhone())) {
                mark.setPhone(borrowuser.getPhone());
            }
            //设置利息管理月率
            Param param = markMapper.findParamByName("利息管理月率");
            if(param!=null){
                double v = param.getValues() / (100*1.0d);
                mark.setManageProRate(v);
            }else {
                mark.setManageProRate(0.01d);
            }

            //取出图片
            List<String> img = mark.getImg();
            List<String> materialImg = mark.getMaterialImg();
            mark.setState("新标草稿");
            mark.setInsertTime(new Timestamp(System.currentTimeMillis()));
            Long aLong = markMapper.addMark(mark);
            if (img!=null && img.size()!=0) {
                for (String name : img) {
                    MarkImgs markImgs = new MarkImgs();
                    markImgs.setMid(mark.getId());
                    markImgs.setImgName(name);
                    markImgs.setState(2);
                    markImgsMapper.add(markImgs);
                }
            }
            if (materialImg!=null && materialImg.size()!=0) {
                for (String name : materialImg) {
                    MarkImgs markImgs = new MarkImgs();
                    markImgs.setMid(mark.getId());
                    markImgs.setImgName(name);
                    markImgs.setState(1);
                    markImgsMapper.add(markImgs);
                }
            }
            return;
        }
        throw new MyException(ExceptionCode.NO_ID);

    }

    @Override
    public List<Map> findAllLikeByPageByXW(String markName, String debtor, String phone, String state, Integer page, Integer size) {
        if("".equals(state)){
            state =null;
        }
        List<Map> allLikeByPageXW = markMapper.findAllLikeByPageXW(markName, debtor, phone, state, null, (page - 1) * size, size,"xw");
        return allLikeByPageXW;
    }

    @Override
    public Integer findAllLikeXWCount(String markName, String debtor, String phone, String state) {
        if ("".equals(state)) {
            state=null;
        }
        Integer allLikeCount = markMapper.findAllLikeCount(markName, debtor, phone, state, null,"xw");

        return allLikeCount;
    }


    @Override
    public List<Map> findAllLikeByPageJK(String debtor, String phone, String diYaType, Integer page, Integer size) {
        List<Map> allLikeByPageXW = markMapper.findAllLikeByPageXW(null, debtor, phone, null, diYaType, (page - 1) * size, size,"jk");
        return allLikeByPageXW;
    }

    @Override
    public Integer findAllLikeJKCount(String debtor, String phone, String diYaType) {
        Integer allLikeCount = markMapper.findAllLikeCount(null, debtor, phone, null, diYaType,"jk");

        return allLikeCount;
    }

    @Override
    public List<Map> findAllLikeByPageSJ(String debtor, String phone, String diYaType, Integer page, Integer size) {
        List<Map> allLikeByPageXW = markMapper.findAllLikeByPageXW(null, debtor, phone, null, diYaType, (page - 1) * size, size,"sj");
        return allLikeByPageXW;
    }

    @Override
    public Integer findAllLikeSJCount(String debtor, String phone, String diYaType) {
        Integer allLikeCount = markMapper.findAllLikeCount(null, debtor, phone, null, diYaType,"sj");
        return allLikeCount;
    }

    @Override
    public Mark findById(Long id) throws MyException {
        Mark byId = markMapper.findById(id);
        if (byId!=null) {
            //不为空，添加图片
            List<String> imgs = new ArrayList<>();
            List<String> materialImgs = new ArrayList<>();
            List<MarkImgs> imgsByMid = markImgsMapper.findImgsByMid(id);
            for (MarkImgs markImgs : imgsByMid) {
                Integer state = markImgs.getState();
                if (state==1) {
                    materialImgs.add(markImgs.getImgName());
                }
                if(state==2){
                    imgs.add(markImgs.getImgName());
                }
            }
            byId.setImg(imgs);
            byId.setMaterialImg(materialImgs);
            return byId;
        }
        throw new MyException(ExceptionCode.NO_ID);
    }

    @Override
    public void deleteById(Long id) throws MyException {
        Mark byId = markMapper.findById(id);
        if (byId!=null) {
            markMapper.deleteById(id);
            return;
        }
        //未发现用户异常
        throw new MyException(ExceptionCode.NO_ID);
    }

    @Override
    public void checkFirstById(Long id, Boolean path, String reason) {
        String state = "初审不通过";
        if (path) {
            state = "新标待上架";
        }
        //初审时间
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        markMapper.checkFirstById(id,state,reason,timestamp);
    }

    @Override
    public List<Investrecord> findAllLikeByPageTZ(String phone, String name, Timestamp from, Timestamp to, Integer page, Integer size, String state1, String state2, String state3, String state4, String state5, String state6) {
        List<Investrecord> allLikeByPageTZ = markMapper.findAllLikeByPageTZ(phone, name, from, to,(page - 1) * size, size, state1, state2, state3, state4, state5, state6);
        return allLikeByPageTZ;
    }

    @Override
    public void fillById(Mark mark) {
        //状态位
        String state = "募集中";
        Timestamp shelfTime = mark.getShelfTime();
        Timestamp nowTime = new Timestamp(System.currentTimeMillis());
        if (nowTime.before(shelfTime)) {
            state = "上架时间未到";
        }
        mark.setState(state);
        markMapper.fillById(mark);

    }

/*    @Override
    public List<Investrecord> findAllLikeByPageTZ(String phone, String name, Timestamp from, Timestamp to, Integer page, Integer size, String state1, String state2, String state3, String state4, String state5, String state6) {
        List<Investrecord> allLikeByPageTZ = markMapper.findAllLikeByPageTZ(phone, name, from, to, (page - 1) * size, size, state1, state2, state3, state4, state5, state6);
        return allLikeByPageTZ;
    }*/

    @Override
    public List<Investrecord> findAllLikeByPageTZExport(String phone, String name, Timestamp from, Timestamp to, String state1, String state2, String state3, String state4, String state5, String state6) {
        List<Investrecord> allLikeByPageTZExport = markMapper.findAllLikeByPageTZExport(phone, name, from, to, state1, state2, state3, state4, state5, state6);
        return allLikeByPageTZExport;
    }

    @Override
    public Integer findAllLikeByPageTZCount(String phone, String name, Timestamp from, Timestamp to,  String state1, String state2, String state3, String state4, String state5, String state6) {
        Integer allLikeByPageTZCount = markMapper.findAllLikeByPageTZCount(phone, name, from, to, state1, state2, state3, state4, state5, state6);
        return allLikeByPageTZCount;

    }

    @Override
    public Map totalBorrow() {
        HashMap<String, Object> totalBorrow = new HashMap<>();

        Calendar now = Calendar.getInstance();
        //获取前一天的开始时间
        now.add(Calendar.DATE,-1);
        now.set(now.get(Calendar.YEAR),now.get(Calendar.MONTH),now.get(Calendar.DAY_OF_MONTH),0,0,0);
        Timestamp timestamp = new Timestamp(now.getTimeInMillis());


        now.add(Calendar.DATE,1);
        now.set(now.get(Calendar.YEAR),now.get(Calendar.MONTH),now.get(Calendar.DAY_OF_MONTH),0,0,0);
        Timestamp timestamp1 = new Timestamp(now.getTimeInMillis());


        //昨日借款总额
        Double newBorrowYesterday = markMapper.findNewBorrowYesterday(timestamp, timestamp1);
        totalBorrow.put("yesterdayBorrow",newBorrowYesterday);

        //总借款额
        Double allBorrow = markMapper.findAllBorrow();
        totalBorrow.put("totalBorrow",allBorrow);
        return totalBorrow;
    }

    @Override
    public Integer todayBackMoney() {
        int size = todayBackByDay().size();
        int size1 = todayBackByMonth().size();
        int size2 = todayBackByOnce().size();
        return size+size1+size2;
    }

    @Override
    public List<Double> totalInvestNearMonth() {
        Calendar calendar = Calendar.getInstance();
        ArrayList<Double> doubles = new ArrayList<>();
        //时间滚到一个月之前
        calendar.add(Calendar.MONTH,-1);
        Timestamp start = new Timestamp(calendar.getTimeInMillis());
        //为了方便计算第2.4.8.12.16.。。30再往后移动2天
        calendar.add(Calendar.DAY_OF_MONTH,-2);
        for(int i = 2;i<=30;i=i+4){
            calendar.add(Calendar.DAY_OF_MONTH,4);
            Timestamp day2 = new Timestamp(calendar.getTimeInMillis());
            Double investFromTo = markMapper.findInvestFromTo(start, day2);
            if(investFromTo==null){
                investFromTo = 0.0;
            }
            doubles.add(investFromTo);
        }
        return doubles;
    }

    //今日待还----按天还款人数
    List<Mark> todayBackByDay(){
        //按出 取出所有按日付款的人
        List<Mark> dayMark = markMapper.findByState("按天");
        //按日夫款需要还钱的人
        List<Mark> needDay = new ArrayList<>();

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH,1);
        calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH),0,0,0);
        //今晚12点的时间搓
        long now = calendar.getTimeInMillis();
        //刷新
        calendar = Calendar.getInstance();

        for (int i=0;i<dayMark.size();i++) {
            //当前计算的mark
            Mark mark = dayMark.get(i);
            //复审发钱时间
            Date checkBTime = mark.getCheckBTime();
            //复审时间进入日历
            calendar.setTime(checkBTime);
            //日历滚动到还款时间
            calendar.add(Calendar.DAY_OF_MONTH,Integer.valueOf(mark.getLoanTerm()));
            //mark复审时间改为还款时间
            mark.setCheckBTime(new Timestamp(calendar.getTimeInMillis()));
            //还款时间-今夜12时间
            long abs =calendar.getTimeInMillis() - now;
            //大于0说明今夜12时间处于还款时间之前，今天因该还
            //Math.abs(abs)<86400000 说明还款时间比今夜12点早，但是也在今天之内
            if(abs>0 || Math.abs(abs)<86400000L){
                Repayrecord byTime = repaymentMapper.findByTime(mark.getName(),new Timestamp(now - 86400000),new Timestamp(now));
                //今日未还（今天没有还款记录）
                if(byTime==null){
                    needDay.add(mark);
                }
            }
        }
        return needDay;
    }

    //今日待还---按月还款/等额本息
    List<Mark> todayBackByMonth(){
        List<Mark> dayMark = markMapper.findByState("按月");
        dayMark.addAll(markMapper.findByState("等额本息"));
        //该换得人
        List<Mark> marks = new ArrayList<>();

        Calendar calendar = Calendar.getInstance();
        //今天的号数
        int today = calendar.get(Calendar.DAY_OF_MONTH);
        calendar.add(Calendar.DAY_OF_MONTH,1);
        calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH),0,0,0);
        //今晚12点的时间搓
        long now = calendar.getTimeInMillis();
        //刷新
        calendar = Calendar.getInstance();
        for (int i = 0; i < dayMark.size(); i++) {
            Mark mark = dayMark.get(i);
            //复审发钱时间
            Date checkBTime = mark.getCheckBTime();
            //设置为发款日
            calendar.setTime(checkBTime);
            if (Math.abs(calendar.getTimeInMillis()-now)<=86400000) {
                continue;
            }
            //取出发款日的  号数  例如上个月5号借钱，即5
            int backTime = calendar.get(Calendar.DAY_OF_MONTH);
            //日历滚动到最后一个月还款日的后一天
            calendar.add(Calendar.MONTH, Integer.valueOf(mark.getLoanTerm()));
            calendar.add(Calendar.DAY_OF_MONTH,1);
            calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH),0,0,0);

            //还款日是今天 且今天在还款日内
            if(calendar.getTimeInMillis()>=now && backTime==today){
                Repayrecord byTime = repaymentMapper.findByTime(mark.getName(), new Timestamp(now - 86400000), new Timestamp(now));
                //还没还的
                if(byTime==null){
                    marks.add(mark);
                }
            }
        }
        return marks;
    }

    //一次性还款---今日还款人数
    List<Mark> todayBackByOnce(){
        List<Mark> dayMark = markMapper.findByState("一次性");

        List<Mark> marks = new ArrayList<>();

        Calendar calendar = Calendar.getInstance();
        //今天的号数
        int today = calendar.get(Calendar.DAY_OF_MONTH);
        calendar.add(Calendar.DAY_OF_MONTH,1);
        calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH),0,0,0);
        //今晚12点的时间搓
        long now = calendar.getTimeInMillis();
        //刷新
        calendar = Calendar.getInstance();
        for (int i = 0; i < dayMark.size(); i++) {
            Mark mark = dayMark.get(i);
            //发钱日期
            Date checkBTime = mark.getCheckBTime();
            //日历滚动到审核发钱日期
            calendar.setTime(checkBTime);
            //取出期限类型
            String loanType = mark.getLoanType();
            //滚动发一次性还款日
            if ("月".equals(loanType)) {
                calendar.add(Calendar.MONTH,Integer.valueOf(mark.getLoanTerm()));
            }
            if ("日".equals(loanType)) {
                calendar.add(Calendar.DAY_OF_MONTH,Integer.valueOf(mark.getLoanTerm()));
            }
            //还款时间减去-今夜12点
            long abs = calendar.getTimeInMillis()-now;
            //大于0说明今夜12时间处于还款时间之前，今天因该还
            //Math.abs(abs)<86400000 说明还款时间比今夜12点早，但是也在今天之内
            if(abs>0 || Math.abs(abs)<86400000L){
                Repayrecord byTime = repaymentMapper.findByTime(mark.getName(),new Timestamp(now - 86400000),new Timestamp(now));
                //今日未还（今天没有还款记录）
                if(byTime==null){
                    marks.add(mark);
                }
            }
        }
        return marks;
    }


    @Override
    public Borrowuser findBorrowById(Long id){
        Borrowuser borrowById = markMapper.findBorrowById(id);
        return borrowById;
    }


}
